﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace DeviceSync
{
	public class FileScanner
	{
		private Dictionary<string, DateTime> files = new Dictionary<string, DateTime>(100);

		public FileScanner()
		{
		}

		/// <summary>
		/// Does this file exist in the local sync log?
		/// </summary>
		public bool CheckFile(FileInfo info)
		{
			DateTime dt;
			if (files.TryGetValue(info.FullName.ToLower(), out dt))
			{
				return (info.LastWriteTime == dt);
			}
			else
				return false;
		}

		/// <summary>
		/// Returns files not in the local cache
		/// </summary>
		public IEnumerable<FileInfo> UnsyncedFiles(IEnumerable<FileInfo> localfiles)
		{
			foreach (FileInfo info in localfiles)
				if (!CheckFile(info))
					yield return info;
		}

		/// <summary>
		/// Record this file as synced
		/// </summary>
		public void AddFile(FileInfo info)
		{
			files[info.FullName.ToLower()] = info.LastWriteTime;
		}

		/// <summary>
		/// Read local sync log from local store
		/// </summary>
		public void LoadCache(string fname)
		{
			if (!File.Exists(fname)) return;

			using (StreamReader sr = new StreamReader(fname))
			{
				String line;
				while ((line = sr.ReadLine()) != null)
					if (line.Contains(","))
					{
						string[] temp = line.Split(',');
						if (temp.Length < 2) continue;
						files[temp[0].ToLower().Replace('*',',')] = DateTime.ParseExact(temp[1], "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
					}
			}
		}

		/// <summary>
		/// Save local sync log to local store
		/// </summary>
		public void SaveCache(string fname)
		{
			using (StreamWriter sw = new StreamWriter(fname, false))
			{
				foreach (KeyValuePair<string, DateTime> kv in files)
				{
					sw.WriteLine("{0},{1}", kv.Key.Replace(',','*'), kv.Value.ToString("yyyy/MM/dd HH:mm:ss"));
				}
			}
		}
	}
}
